package com.quicklife.action.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 关于：
 *	限制权限不足的用户不能访问 register.jsp 和 login.jsp 外的网页
 * @author AF130310  修改日期：2013-10-19
 *
 */
public class WebPermissionFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		// 取得用户要访问的绝对路径
		String uri = request.getRequestURI();
		String target = uri.substring(uri.indexOf("/", 1), uri.length());
		Object roleid = request.getSession().getAttribute("roleid");
		
		// 访问 /admin 跟 /manage 两个目录下文件的要进行访问限制
		if (target.startsWith("/admin")) {
			if ( roleid == null || (Integer)roleid != 0 ) {
				response.sendRedirect("/QuickLifeServer/login.jsp");
			}
		} else if (target.startsWith("/manage")) {
			if (roleid == null || ((Integer) roleid != 1 && (Integer) roleid != 2)) {
				response.sendRedirect("/QuickLifeServer/login.jsp");
			}
		}
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
